/**
 * Copyright &copy; 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package com.thinkgem.jeesite.modules.book.web;
import com.thinkgem.jeesite.common.persistence.DataEntity;
import com.thinkgem.jeesite.common.persistence.Page;
import com.thinkgem.jeesite.common.persistence.Result;
import com.thinkgem.jeesite.common.utils.DateUtils;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.common.utils.excel.ExportExcel;
import com.thinkgem.jeesite.common.web.BaseController;
import com.thinkgem.jeesite.modules.book.entity.*;
import com.thinkgem.jeesite.modules.book.service.BookMgrService;
import com.thinkgem.jeesite.modules.book.service.BookPurchaseService;
import com.thinkgem.jeesite.modules.book.service.BookStoreService;
import com.thinkgem.jeesite.modules.book.service.PrintTemplateService;
import com.thinkgem.jeesite.modules.sys.utils.UserUtils;
import org.apache.commons.collections.CollectionUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 采购Controller
 *
 * @author zc
 * @version 2013-11-03
 */
@Controller
@RequestMapping(value = "${adminPath}/book/purchase")
public class BookPurchaseController extends BaseController{

    @Autowired
    private BookPurchaseService bookPurchaseService;
    @Autowired
    private BookMgrService bookMgrService;
    @Autowired
    private BookStoreService bookStoreService;

    @Autowired
    private PrintTemplateService printTemplateService;

    @ModelAttribute
    public BkPurchaseBatch get(@RequestParam(required = false) String batchId){
        if(StringUtils.isNotBlank(batchId)){
            return bookPurchaseService.get(batchId);
        }
        else{
            return new BkPurchaseBatch();
        }
    }

    @RequiresPermissions("book:purchase:view")
    @RequestMapping(value = "form")
    public String form(BkPurchaseBatch bkPurchaseBatch,Model model){
        model.addAttribute("bkPurchaseBatch",bkPurchaseBatch);
        return "modules/book/bookPurchaseForm";
    }

    /**
     * 查询批次信息
     *
     * @param batchId 批次编号
     * @param model   model
     * @return 跳转页面
     */
    @RequestMapping(value = "batch")
    public String batch(String batchId, HttpServletRequest request, HttpServletResponse response, Model model){
        BkPurchaseBatch bkPurchaseBatch = bookPurchaseService.get(batchId);

        Page<BkPurchaseBatchDetail> page = bookPurchaseService.findDetails(new Page<BkPurchaseBatchDetail>(request, response), batchId);
        model.addAttribute("page", page);

        model.addAttribute("bkPurchaseBatch", bkPurchaseBatch);
        return "modules/book/bookPurchaseBatch";
    }

    @RequestMapping(value = {"list", ""})
    public String list(BkPurchaseBatch bkPurchaseBatch, HttpServletRequest request, HttpServletResponse response, Model model){
        Page<BkPurchaseBatch> page = bookPurchaseService.findPage(new Page<BkPurchaseBatch>(request, response), bkPurchaseBatch);
        model.addAttribute("page", page);
        BkPurchaseBatch bkbatch = new BkPurchaseBatch();
        bkbatch.setStatus("work");
        bkbatch = bookPurchaseService.getCurrentWorkBatch(bkbatch);
        model.addAttribute("currentworkbatch",bkbatch);
        return "modules/book/bookPurchaseList";
    }

    /**
     * 新增登到计划
     *
     * @param request
     * @param model
     * @return
     */
    @RequiresPermissions("book:purchase:save")
    @RequestMapping("saveplan")
    @ResponseBody
    public Result savePlan(HttpServletRequest request, Model model){
        String param = request.getParameter("param");
        return bookPurchaseService.savePlan(param);
    }

    /**
     * 新增验收批次
     *
     * @param bkPurchaseBatch
     * @param redirectAttributes
     * @param model
     * @return
     */
    @RequiresPermissions("book:purchase:save")
    @RequestMapping("addPurchase")
    public String addPurchase(BkPurchaseBatch bkPurchaseBatch, Model model, RedirectAttributes redirectAttributes){
        if (!beanValidator(model, bkPurchaseBatch)){
            return form(bkPurchaseBatch, model);
        }
        //设置验收批次为验收中
        bkPurchaseBatch.setStatus(BkPurchaseBatch.STATUS_CHECK);
        bkPurchaseBatch.setPlanDate(DateUtils.parseDate(DateUtils.getDateTime()));
        bkPurchaseBatch.setBatchDate(DateUtils.parseDate(DateUtils.getDateTime()));
        bookPurchaseService.save(bkPurchaseBatch);
        addMessage(redirectAttributes, "保存验收批次'" + bkPurchaseBatch.getBatchNumber() + "'成功");
        return "redirect:" + adminPath + "/book/purchase/list/?repage";
    }

    /**
     * 验收完成后的结果页面
     *
     * @param batchId
     * @param bkId
     * @return
     */
    @RequiresPermissions("book:purchase:save")
    @RequestMapping("addPurchaseDetail")
    public String addPurchaseDetail(String batchId, String bkId, Model model){
        BkBookinfo bookinfo = bookMgrService.get(bkId);
        if(null != bookinfo){
        model.addAttribute("bookinfo", bookinfo);
        String classcode = bookinfo.getClasscode();
        String books = bookinfo.getBooks();
        if(StringUtils.isNotEmpty(books)){
            bookinfo.setClassName(classcode);
            String temClasscode = bookStoreService.getFirstClasscodeByBooks(books);
            classcode = StringUtils.defaultIfEmpty(temClasscode, classcode);
            bookinfo.setClasscode(classcode);
        }
        BkBookstore store = new BkBookstore(bookinfo);
        store.setBatch(batchId);
        store.setAmount(1);
        store.setBooksAmount(1);
        model.addAttribute("store", store);

        BkPurchaseBatch batch = bookPurchaseService.get(batchId);

        boolean isBooks = StringUtils.isNotBlank(bookinfo.getBooks());
        String booksNum = bookinfo.getBooksNum();
        String place = bookPurchaseService.createPlace(bkId, classcode, isBooks, booksNum);
        model.addAttribute("place", place);

        model.addAttribute("batch", batch);

        String loginName = UserUtils.getUser().getLoginName();
        String maxBarCode = bookStoreService.getMaxBarCodeByUser(loginName);
        model.addAttribute("maxBarCode", maxBarCode);
        }
        return "modules/book/pop/purchaseDetailEdit";
    }

    /**
     * 生成索书号
     *
     * @param classcode
     * @return
     */
    @RequestMapping("createPlace")
    @ResponseBody
    public String checkPlace(String bkId,String classcode,boolean isBooks,String booksNum){
        return bookPurchaseService.createPlace(bkId, classcode, isBooks, booksNum);
    }

    /**
     * 检查索书号
     *
     * @param classcode
     * @return
     */
    @RequiresPermissions("book:purchase:view")
    @RequestMapping("checkPlace")
    public String checkPlace(String classcode, Model model){
        model.addAttribute("classcode",classcode);
        String[] str = classcode.split("/");
        classcode = str[0];
        String place = null;
        if(str.length >= 2){
            place = str[1];
        }
        List<BkBookstore> stores = bookStoreService.findStoresByClasscode(classcode, place);

        model.addAttribute("stores", stores);
        return "modules/book/pop/placeCheck";
    }

    /**
     * 查询批次信息
     *
     * @param batchId 批次编号
     * @param model   modelf
     * @return 跳转页面
     */
    @RequestMapping(value = "gotoEdit")
    public String gotoEdit(String batchId, HttpServletRequest request, HttpServletResponse response,Model model)
            throws UnsupportedEncodingException, ParseException{
        BkPurchaseBatch bkPurchaseBatch;
        if(StringUtils.isEmpty(batchId)){
            BkPurchaseBatch bkbatch = new BkPurchaseBatch();
            bkbatch.setStatus("work");
            bkPurchaseBatch = bookPurchaseService.getCurrentWorkBatch(bkbatch);
        }
        else{
            bkPurchaseBatch = bookPurchaseService.get(batchId);
        }
        if(null != bkPurchaseBatch){
            batchId = String.valueOf(bkPurchaseBatch.getBatchId());
            bkPurchaseBatch.setDetails(bookPurchaseService.findDetails(new Page<BkPurchaseBatchDetail>(request, response), batchId).getList());
            String remarks = bkPurchaseBatch.getRemarks();
            if(StringUtils.isNotEmpty(remarks)){
                bkPurchaseBatch.setRemarks(URLDecoder.decode(remarks, "utf-8"));
            }

            model.addAttribute("bkPurchaseBatch", bkPurchaseBatch);
            return "modules/book/bookPurchaseEdit";
        }
        else{
            return "redirect:" + adminPath + "/book/purchase/list";
        }
    }


    @RequiresPermissions("book:purchase:save")
    @RequestMapping(value = "check")
    public String check(RedirectAttributes redirectAttributes, BkBookstore store, String autoCreateBanId){
        String bkId = store.getBkId();
        String batch = store.getBatch();

        BkBookinfo bookinfo = bookMgrService.get(bkId);

        BkPurchaseBatchDetail detail = new BkPurchaseBatchDetail(
                Integer.parseInt(batch),
                bkId,
                bookinfo.getIsbn(),
                Double.valueOf(store.getpPrice()),
                Double.valueOf(store.getRealPrice()),
                store.getAmount(),
                store.getBooksAmount(),
                bookinfo.getBookname(),
                bookinfo.getClasscode(),
                bookinfo.getOthername());


        String result = "书目入库成功！";
        try{
            bookStoreService.saveStore(detail, store, autoCreateBanId);
        }
        catch(Exception e){
            logger.error("书目入库失败", e);
            result = "书目入库失败！原因：" + e.getMessage();
        }
        addMessage(redirectAttributes, result);
        return "redirect:" + adminPath + "/book/store/checkList?bkId=" + bkId + "&batch=" + batch + "&pbdId=" + detail.getPbdId();
    }

    /**
     * 登到
     *
     * @param batchId
     * @param batchDate
     * @param remarks
     * @param request
     * @return Result
     */
    @RequiresPermissions("book:purchase:save")
    @RequestMapping("save")
    @ResponseBody
    public Result savePurchase(String batchId, String batchDate, String remarks, HttpServletRequest request){
        String param = request.getParameter("param");
        return bookPurchaseService.savePurchase(batchId, batchDate, remarks, param);
    }

    /**
     * 取消登到
     *
     * @param batchId
     * @return Result
     */
    @RequiresPermissions("book:purchase:save")
    @RequestMapping("cancel")
    @ResponseBody
    public Result cancelPlan(String batchId){
        return bookPurchaseService.cancelPlan(batchId);
    }
    /**
     * 删除采访
     *
     * @param batchId 批次编号
     */
    @RequiresPermissions("book:purchase:delete")
    @RequestMapping("delete")
    @ResponseBody
    public Result delete(String batchId){
        try{
            BkPurchaseBatch bkPurchaseBatch = new BkPurchaseBatch();
            bkPurchaseBatch.setBatchId(Integer.parseInt(batchId));
            bkPurchaseBatch.setDelFlag(DataEntity.DEL_FLAG_DELETE);
            bkPurchaseBatch.preUpdate();
            bookPurchaseService.deleteBatch(bkPurchaseBatch);
            bookPurchaseService.deleteDetail(bkPurchaseBatch);
            return new Result("删除批次成功！");
        }
        catch(Exception e){
            return new Result("0002","删除批次失败！","");
        }
    }

    /**
     * 删除批次详情
     *
     * @param pbdId 批次编号
     */
    @RequiresPermissions("book:purchase:delete")
    @RequestMapping("deleteDetail")
    @ResponseBody
    public Result deleteDetail(String pbdId){
        int result = bookPurchaseService.deleteDetailbyId(pbdId);
        if(result > 0){
            return new Result(Result.SUCCESS, "删除批次数据成功！", null);
        }
        else{
            return new Result(Result.FAILURE, "删除批次数据失败！", null);
        }
    }

    /**
     * 设置工作验收批次
     *
     * @param request
     */
    @RequiresPermissions("book:purchase:save")
    @RequestMapping("setworkbatch")
    public String setworkBatch(HttpServletRequest request, Model model){
        String batchid=request.getParameter("workbatchid");
        BkPurchaseBatch bkPurchaseBatch = new BkPurchaseBatch();
        bkPurchaseBatch.setBatchId(Integer.parseInt(batchid));
        bkPurchaseBatch.setStatus(BkPurchaseBatch.STATUS_WORK);
        bookPurchaseService.updateOtherWorkStatus();
        bookPurchaseService.updateStatus(bkPurchaseBatch);

        return "redirect:" + adminPath + "/book/purchase/list/?repage";
    }
    /**
     * 结束验收批次
     *
     * @param request
     */
    @RequiresPermissions("book:purchase:save")
    @RequestMapping("confirmBatch")
    public String confirmBatch(HttpServletRequest request, Model model){
        String batchid=request.getParameter("workbatchid");
        BkPurchaseBatch bkPurchaseBatch = new BkPurchaseBatch();
        bkPurchaseBatch.setBatchId(Integer.parseInt(batchid));
        bkPurchaseBatch.setStatus(BkPurchaseBatch.STATUS_OVER);
        bookPurchaseService.updateStatus(bkPurchaseBatch);

        return "redirect:" + adminPath + "/book/purchase/list/?repage";
    }


    /**
     * 跳转设置图书条码初始值页面
     * @param model
     * @return
     */
    @RequestMapping("gotoSetUpStartBanId")
    public String gotoSetUpStartBanId(Model model){
        List<BkBookBan> bookBanList = bookStoreService.getBookBanList();
        model.addAttribute("bookBanList", bookBanList);
        String loginName = UserUtils.getUser().getLoginName();
        model.addAttribute("loginName", loginName);
        return "modules/book/bookStartBanId";
    }

    /**
     * 跳转设置图书条码初始值页面
     * @param startsn
     * @return
     */
    @RequestMapping("setUpStartBanId")
    @ResponseBody
    public Result setUpStartBanId(String startsn){
        String loginName = UserUtils.getUser().getLoginName();

        boolean result = bookPurchaseService.isSetUpStartBanId(loginName);
        int inresult;
        if(result){
            inresult = bookPurchaseService.updateStartBanId(startsn, loginName);
        }
        else{
            inresult = bookPurchaseService.saveStartBanId(startsn, loginName);
        }

        if(inresult >= 1){
            return new Result("设置成功！");
        }else{
            return new Result(Result.FAILURE, "设置失败！", null);
        }
    }

    /**
     * 查看是否设置图书条码初始值
     *
     * @return
     */
    @RequestMapping("isSetUpStartBanId")
    @ResponseBody
    public Result isSetUpStartBanId(){
        String loginName = UserUtils.getUser().getLoginName();
        boolean result = bookPurchaseService.isSetUpStartBanId(loginName);
        if(result){
            return new Result("设置成功！");
        }
        else{
            return new Result(Result.FAILURE, "设置失败！", null);
        }
    }

    /**
     * 跳转图书条码打印页面
     * @param model
     * @return
     */
    @RequiresPermissions("book:purchase:save")
    @RequestMapping("printsn")
    public String printsn(String banIds, Model model){
        BkBookBan bookBan = bookPurchaseService.getMaxPrintbanId();

        String pStr = "";
        if(null != bookBan){
            String startsn = bookBan.getBanId();
            if("N".equals(bookBan.getStatus())){
                pStr = startsn;
            }
            else{
                if(StringUtils.isNotEmpty(startsn)){
                    char[] startsns = startsn.toCharArray();
                    int index = 1;
                    for(int i = startsns.length - 1; i >= 0; i--){
                        char sn = startsns[i];
                        if(sn != '9'){
                            index = i;
                            break;
                        }
                    }
                    pStr = startsn.substring(0, index);
                    String nStr = startsn.substring(index);
                    Long n = Long.parseLong(nStr) + 1;
                    pStr = pStr + n;
                }
            }

            model.addAttribute("startsn", pStr);
            model.addAttribute("school", bookBan.getSchool());
        }
        model.addAttribute("banIds", StringUtils.defaultIfEmpty(banIds,""));

        return "modules/book/bookSnPrint";
    }

    /**
     * 保存打印数据
     *
     * @return
     */
    @RequiresPermissions("book:purchase:save")
    @RequestMapping("savePrint")
    public void savePrint(String startsn, String endsn, String school){
        bookPurchaseService.savePrint(startsn, endsn, school);
    }

    /**
     * 跳转书标打印页面
     *
     * @return
     */
    @RequiresPermissions("book:purchase:save")
    @RequestMapping("toPrintPlace")
    public String toPrintPlace(){
        return "modules/book/bookPlacePrint";
    }

    /**
     * 跳转书标打印页面
     *
     * @return
     */
    @RequiresPermissions("book:purchase:save")
    @RequestMapping("printPlace")
    public String printPlace(String batchNum, String snBegin, String snEnd, String storeIds, Model model){
        List<BkBookstore> bookstores = searchBookstores(batchNum, snBegin, snEnd, storeIds);

        model.addAttribute("batchNum", batchNum)
                .addAttribute("snBegin", snBegin)
                .addAttribute("snEnd", snEnd)
                .addAttribute("storeIds", storeIds)
                .addAttribute("size", bookstores.size());

        try{
            List<PrintTemplate> printTemplates = printTemplateService.searchPrintTemplates();
            if(CollectionUtils.isNotEmpty(printTemplates)){
                model.addAttribute("printTemplate", printTemplates.get(0));
            }
            else{
                PrintTemplate template = new PrintTemplate();
                template.setName("默认");
                template.setWidth(210);
                template.setHeight(297);
                template.setItemWidth(43);
                template.setItemHeight(15);
                template.setItemTop(0);
                template.setItemLeft(40);
                template.setxMove(165);
                template.setyMove(94);
                template.setLineSize(4);
                template.setPageNum(40);
                printTemplateService.save(template);
                model.addAttribute("printTemplate", template);
            }
        }
        catch(Exception e){
            logger.error("查询打印信息错误：", e);
        }

        return "modules/book/bookPlacePrintDesign";
    }

    /**
     * 跳转书标打印页面
     *
     * @return
     */
    @RequiresPermissions("book:purchase:save")
    @RequestMapping("savePrintPlace")
    @ResponseBody
    public Result savePrintPlace(PrintTemplate printTemplate){
        try{
            printTemplateService.save(printTemplate);
        }
        catch(Exception e){
            logger.error("保存打印信息错误：", e);
            return Result.error("保存打印信息错误");
        }
        return Result.success("保存打印信息成功");
    }

    /**
     * 跳转书标打印页面
     *
     * @return
     */
    @RequiresPermissions("book:purchase:save")
    @RequestMapping("searchPlace")
    @ResponseBody
    public Result searchPlace(String batchNum, String snBegin, String snEnd, String storeIds){
        List<BkBookstore> bookstores = searchBookstores(batchNum, snBegin, snEnd, storeIds);
        return new Result(Result.SUCCESS, "查询成功", bookstores);
    }

    private List<BkBookstore> searchBookstores(String batchNum, String snBegin, String snEnd, String storeIds){
        List<BkBookstore> bookstores;
        if(StringUtils.isEmpty(storeIds)){
            bookstores = bookStoreService.searchBookstores(batchNum, snBegin, snEnd);
        }
        else{
            if(storeIds.endsWith(",")){
                storeIds = storeIds.substring(0, storeIds.length() - 1);
            }
            bookstores = bookStoreService.searchBookstoresByIds(storeIds);
        }

        return bookstores;
    }
    /**
     * 查询验收单
     * @param begin
     * @param end
     * @param batchId
     * @param model
     * @return
     */
    @RequiresPermissions("book:purchase:view")
    @RequestMapping("purchaseLedger")
    public String purchaseLedger(String begin, String end, String batchId, Model model){

        BkPurchaseBatch purchase = bookPurchaseService.get(batchId);
        model.addAttribute("purchase", purchase);

        List<BkBookstore> generalledger = bookStoreService.getPurchaseLedger(begin, end, batchId, 100);
        model.addAttribute("generalledger", generalledger);



        model.addAttribute("batchId", batchId);
        model.addAttribute("begin", begin);
        model.addAttribute("end", end);

        Map<String,String> ledgerAmount = bookStoreService.getPurchaseLedgerAmount(begin, end, batchId);
        model.addAttribute("ledgerAmount", ledgerAmount);


        List<BkPurchaseBatch> all = bookPurchaseService.findList(null);
        for(BkPurchaseBatch batch : all){
            batch.setRemarks("");
            if(StringUtils.isNotEmpty(batchId) && Integer.parseInt(batchId) == batch.getBatchId()){
                batch.setRemarks("selected");
            }
        }
        model.addAttribute("all", all);
        return "modules/book/purchaseLedger";
    }

    /**
     * 导出Excel
     * @param begin
     * @param end
     * @param batchId
     * @param response
     * @return
     */
    @RequiresPermissions("book:purchase:view")
    @RequestMapping(value = "export")
    public String exportExcel(String begin, String end, String batchId, HttpServletResponse response){
        List<BkBookstore> bookstores = bookStoreService.getPurchaseLedger(begin, end, batchId, 0);
        int amount = 0;

        BigDecimal total = new BigDecimal(0);

        List<PurchaseLedger> purchaseLedgers = new ArrayList<>();
        for(BkBookstore store:bookstores){
            amount += store.getAmount();
            PurchaseLedger purchaseLedger = new PurchaseLedger(store);
            purchaseLedger.setNum(String.valueOf(bookstores.indexOf(store)+1));
            purchaseLedgers.add(purchaseLedger);

            total = total.add(new BigDecimal(purchaseLedger.getTotal()));
        }
        try{
            PurchaseLedger purchaseLedger = new PurchaseLedger();
            purchaseLedger.setNum("合计：");
            purchaseLedger.setAmount(String.valueOf(amount));
            purchaseLedger.setTotal(String.valueOf(total));
            purchaseLedgers.add(purchaseLedger);


            String fileName = "验收单" + DateUtils.getDate("yyyyMMddHHmmss") + ".xlsx";
            new ExportExcel("验收单", PurchaseLedger.class).setDataList(purchaseLedgers).write(response, fileName).dispose();
            return null;
        }
        catch(Exception e){
            e.printStackTrace();
        }
        return "redirect:" + adminPath + "/book/purchase/purchaseLedger?repage";
    }
    /**
     * 查询是否有重复的批次编号
     *
     * @return String
     */
    @RequestMapping(value = "checkRepeatBatchNumber")
    @ResponseBody
    public Result checkRepeatBatchNumber(String batchNumber){
        int iCount = bookPurchaseService.checkRepeatBatchNumber(batchNumber);
        if(iCount!=0) {
            return new Result("0002","批次编号已存在！请重新输入！","");
        }
        return new Result("");
    }

    /**
     * 根据 图书编号，查询图书批次信息
     *
     * @return String
     */
    @RequestMapping(value = "findDetailByBkId")
    @ResponseBody
    public BkPurchaseBatchDetail findPurchaseBatchDetailByBkId(String bkId){
       return bookPurchaseService.findPurchaseBatchDetailByBkId(bkId);
    }
}
